package com.eshanren.ext.base;


import com.jfinal.core.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Controller基类
 *
 * @author WWF
 */
public abstract class BaseController extends Controller {

    /**
     * 返回url *
     */
    protected static final String URL = "url";
    /**
     * 请求页面的参数 *
     */
    protected static final String PAGE_NUM = "pageNumber";

    /**
     * 请求的要显示的数据条数参数 *
     */
    protected static final String NUM_PER_PAGE = "pageSize";

    /**
     * 标志位
     */
    public static final String CODE = "code";

    /**
     * 提示消息 *
     */
    public static final String MESSAGE = "msg";


    /**
     * 请求要显示的页数 *
     */
    protected int pageNumber = 1;
    /**
     * 显示的数据条数 *
     */
    protected int pageSize = 10;


    /**
     * 默认index
     */
    public void index() {
        redirect("/");
    }

    /**
     * 获得多个对象
     *
     * @param modelClass
     * @param modelName
     * @param request
     * @param <T>
     * @return
     */
    protected <T> List<T> getModelList(Class<T> modelClass, String modelName, HttpServletRequest request, Controller c) {
        Pattern p = Pattern.compile(modelName + "\\[\\d\\].[a-zA-z0-9]+");
        Map<String, String[]> parasMap = request.getParameterMap();
        String paraKey;
        Set<String> modelPrefix = new HashSet<String>();
        for (Map.Entry<String, String[]> e : parasMap.entrySet()) {
            paraKey = e.getKey();
            if (p.matcher(paraKey).find()) {
                modelPrefix.add(paraKey.split("\\.")[0]);
            }
        }
        List<T> resultList = new ArrayList<T>();
        for (String modelName2 : modelPrefix) {
            resultList.add(c.getModel(modelClass, modelName2));
        }
        return resultList;
    }


}